const default_boyan_header_number = 6
const default_page_index = '2000'
const table_header_names = ['Sub', 'Name', 'Value', 'Type', 'Default', 'Save', 'Comment']
let eds_object
let get_set_value

$(document).ready(function()
{
	configuration = configuration_expert

	const eds_script = utils.load_script('eds.js')
    Promise.all([
		eds_script
	])
	.then(() => eds.get_eds_object())
	.then(getted_eds_object => {
		eds_object = getted_eds_object
		//console.log(eds_object)
		
		get_set_value = new GetSetValue()
		add_autoupdate()
		add_raw_data()
		let selected_page = get_saved_page_index()
		add_pages_menu(selected_page)
		select_page(selected_page)
		show_commit_info()

		$("#boyan").accordion({ heightStyle: 'content', header: '.accordion-header', active: get_saved_menu_number()})
		$("#boyan").accordion( "option", "collapsible", true )
		$(".menu_button").button()

		$(document).on('click', '.autoupdate', function()
		{
			get_set_value.on_autoupdate_click()
		})
		$(window).focus(function() //Во вкладке
		{
			get_set_value.on_windows_focus()
		})
		$(window).blur(function() //Покинули вкладку
		{
			get_set_value.on_windows_blur()
		})
	})
})

function get_saved_page_index()
{
	let selected_page_index = localStorage.getItem("selected_page_index")
	if (selected_page_index == null)
	{
		selected_page_index = default_page_index
	}
	return selected_page_index
}

function get_saved_menu_number()
{
	let selected_boyan_header = localStorage.getItem("selected_accordion_header")
	let boyan_header_number = default_boyan_header_number
	if (selected_boyan_header != null)
	{
		boyan_header_number = Number(selected_boyan_header)/2
	}
	return boyan_header_number
}

function add_autoupdate()
{
	let autoupdate_input = '<label><label class="autoupdate"><span></span></label> Autoupdate</label>'	
	$("#main").append(autoupdate_input)	
}

function add_raw_data()
{
	let main_label = $('<label>')
	let span_label = $('<label class="raw_data"><span></span></label>')

	let searchParams = new URLSearchParams(location.search);
	let raw_data = searchParams.get("raw_data")
	if (raw_data === null)
	{
		span_label.addClass("off")
	}

	main_label.append(span_label).append(' Raw Values')
	$("#main").append('<br>').append(main_label)
}

function add_pages_menu(selected_page_index)
{
	let boyan = $('<div id="boyan">')
	//console.log(eds_object)
	$.each(common.expert_page_dictionary(), function(group_index, group_param)
	{
		let boyan_header = $('<div>').addClass('accordion-header')
		let boyan_body = $('<div>').addClass('accordion-body')

		boyan_header.html(group_param.name + '</br>&nbsp&nbsp&nbsp&nbsp' + group_param.minIndex + ' - ' + group_param.maxIndex )
		let minIndex = parseInt(group_param.minIndex)
		let maxIndex = parseInt(group_param.maxIndex)

		let find_some_index = false
		Object.keys(eds_object).sort().forEach(function(index)
		{
			let int_index = parseInt(`0x${index}`)

			if (int_index >= minIndex && int_index <= maxIndex)
			{
				find_some_index = true
				let index_div = $('<div>').addClass('menu_button')
				let index_str = '#index' + index
				index_div.text('0x' + index + ' ' + eds_object[index].ParameterName)
				index_div.attr({'id':index_str, 'onclick':`select_page('${index}')`})

				if (index == selected_page_index)
				{
					index_div.addClass('selected')
				}
				boyan_body.append(index_div)
			}
		})

		if (find_some_index)
		{
			boyan.append(boyan_header)
			boyan.append(boyan_body)
		}
	})

	$("#main").append(boyan)
}

function select_page(index_number)
{
	common.add_multiply_templates()
	
	//console.log(eds_object)
	let table = $('<table>')
	let	table_name = $('<h4>').addClass('table_name')
	let table_header = $('<tr>').addClass('table_header')

	localStorage.setItem("selected_page_index", index_number)
	$("#second_html").html('') //clear frame

	if (index_number in eds_object)
	{
		let name_comment = ''
		if (eds_object[index_number].Comment != "")
		{
			name_comment = '(' + eds_object[index_number].Comment + ')'
		}

		table_name.html('<b>0x' + index_number + '</b> \"' + eds_object[index_number].ParameterName + '\" ' + name_comment)

		//console.log(eds_object[index_number])
		//console.log(eds_object[index_number].subs)
		if (Object.keys(eds_object[index_number].subs).length > 0)
		{
			let request_array = []
			for(let index in eds_object[index_number].subs) {
				request_array[index] = eds_object[index_number].subs[index]
			}

			//get_set_value = new GetSetValue()
			get_set_value.set_request_data(request_array, ".value")
			get_set_value.send_query()

			$.each(table_header_names, function (table_header_index, table_header_name)
			{
				let column_name = $('<td>').text(table_header_name)
				table_header.append(column_name)
			})
			table.append(table_header)

			//for(let sub_index = 0; sub_index < Object.keys(eds_object[index_number].subs).length; sub_index++)
			for(let key in Object.keys(eds_object[index_number].subs)) 
			{
				let sub_index = Object.keys(eds_object[index_number].subs)[key]
				let sub_item_data = eds_object[index_number].subs[sub_index]

				if (sub_item_data != undefined)
				{
					if (sub_item_data.index != null)
					{
						//let table_row = $('<tr style="border-bottom: solid 1px black">')
						let table_row = $('<tr>')
						if (key % 2 == 0)
						{
							table_row.addClass('marked')
						}
						let index_parts = sub_item_data.index.split(":")
						let index_str = index_parts[1]
						table_row.append($('<td>').text(index_str))
						table_row.append($('<td>').text(sub_item_data.ParameterName))
						table_row.append($('<td>').append(get_set_value.get_cell(sub_index)))
						table_row.append($('<td>').text(sub_item_data.DataType))
						table_row.append($('<td>').text(sub_item_data.DefaultValue))
						if (sub_item_data.Save == "Yes")
						{
							table_row.append($('<td>').text("Settings"))
						}
						else
						{
							table_row.append($('<td>').text(sub_item_data.Save))
						}
						table_row.append($('<td>').text(sub_item_data.Comment))
						table.append(table_row)
					}
				}
			}
		}
	}
	else
	{
		table_name.text(l100n.localize_string("index_error"))
	}

	$("#second_html").append(table_name)
	$("#second_html").append(table)
}

function show_commit_info(){
	let commit_button = $('<div>').addClass('menu_button')
	commit_button.text('Commit info')
	commit_button.attr({ 'onclick':"show_commit_page()"})//'id':'commit_page',
	$("#main").append(commit_button)
}

function show_commit_page()
{
	$("#second_html").html('')
	let dirty = ""
	if (commit_info.commit_info['is_dirty']) 
	{
		dirty = "(M)"
	}
	let system_datetime = new Date(commit_info.commit_info['date_time']*1000)
	let system_commit_date = utils.dateYYYYMMDD(system_datetime)
	let system_commit_time = utils.timeHHmmss(system_datetime)
	$("#second_html").append(`System commit: ${commit_info.commit_info['commit_hash']}${dirty},
		${system_commit_date} ${system_commit_time},
		branch:(${commit_info.commit_info['active_branch']})`)
}

$(function()
{
	$(document).on('click', '.menu_button', function()
	{
        $('.menu_button').removeClass("selected")
        $(this).addClass("selected")
    })

    $(document).on('click', '.accordion-header', function()
	{
        localStorage.setItem("selected_accordion_header", $(this).index())
    })

    $(document).on('mouseover', '.menu_button', function()
	{
        $(this).addClass("hover")
    })

	$(document).on('mouseout', '.menu_button', function()
	{
        $(this).removeClass("hover")
	})

	$(document).on('click', '.raw_data', function()
	{
		let searchParams = new URLSearchParams(location.search)
		let raw_data = searchParams.get("raw_data")

		if (raw_data)
		{
			searchParams.delete("raw_data")
			//$('.raw_data').addClass("off");
		}
		else
		{
			searchParams.append("raw_data", "1")
			//$('.raw_data').removeClass("off")
		}
		document.location.href = `${document.location.pathname}?${searchParams.toString()}`
	})
})